<template>
    <movable-area style="width: 100vw;height: 100vh;">
        <!--拍照区域-->
        <movable-view v-if="practiceSettings.openFaceRecognize && isCameraShow" :x="windowWidth - 100"
            :y="windowHeight - 260" direction="all" style="z-index: 9999999;width: 110px;height: 160px;">
            <ExamPhoto ref="childRef"></ExamPhoto>
        </movable-view>

        <u-navbar :safeAreaInsetTop="true" :placeholder="true" bgColor="#FFF" :fixed="true">
            <view slot="left" style="display: flex;">
                <view
                    style=" line-height: 27px; text-align: center; color: #000;width: 100%;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;margin-left: 20rpx">
                    {{ title || '自测记录' }}
                </view>
            </view>
            <view slot="right" style="margin-right: 200rpx;position: relative;">
                <image style="width: 46rpx;" src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/setUp.svg"
                    mode="" @click="isSetUp = !isSetUp">
                </image>
                <view v-if="isSetUp"
                    style="width: 240rpx;padding:20rpx;box-shadow: 0px 0px 9px 0px #0000001A;position: absolute;top: 300rpx;right: -120rpx;background-color: #fff;">
                    <view style="flex-direction: row;display: flex;justify-content: space-around;"
                        @click="fontModal = true">
                        <image style="width: 32rpx;height: 36rpx;"
                            src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/font.svg" mode="">
                        </image>
                        <text style="margin-left: 20rpx; text-align: center;width: 60%;">字号设置</text>
                    </view>
                    <view style="flex-direction: row;display: flex;margin: 30rpx 0;justify-content: space-around;"
                        @click="showCalculator">
                        <image style="width: 32rpx;height: 36rpx;"
                            src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/calculator.svg" mode="">
                        </image>
                        <text style="margin-left: 20rpx; text-align: center;width: 62%;">计算器</text>
                    </view>
                    <view style="flex-direction: row;display: flex;justify-content: space-around;">
                        <text>自动换题</text>
                        <u-switch v-model="automatic" activeColor="#37B874" size="20"></u-switch>
                    </view>
                </view>
            </view>
        </u-navbar>
        <view v-if="examStatus"
            style="text-align: center;margin-top: 10rpx;display: flex;justify-content:center;position:relative;padding-top: 20rpx;background-color: #fff;">
            <view style="display: flex;width: 100%;justify-content: center;align-items: center;">倒计时：<u-count-down
                    :time="minute * 60 * 1000" autoStart format="HH:mm:ss" @finish="finish"></u-count-down>
            </view>
            <view v-if="!flag" @click="onSubmitModal" style="position: absolute;right: 40rpx;">
                <text style="color: #37B874;">交卷</text>
            </view>
        </view>
        <view
            :style="{ padding: '30rpx 40rpx 60rpx 40rpx', backgroundColor: '#FFF', height: windowHeight - 200 + 'px', overflow: 'auto', }"
            @click="isSetUp = false" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
            <!-- <text style="background-color: #F6FFF7;border-radius: 20rpx 20rpx 20rpx 0;padding: 6rpx 10rpx;">{{
				onChangeDict(showQuestion.type,
					mapDictCodesData.allQuestionType) }}</text> -->
            <text
                style="border: 1px solid #37B874;border-radius: 20px 20px 20px 0;padding: 5rpx 15rpx;background-color: #F3FBF7;display:inline-block;margin:2px 5px 40rpx 0">{{
                    onChangeDict(showQuestion.type,
                        mapDictCodesData.allQuestionType) }}</text>
            <view style="border-radius: 10rpx;  padding-top: 10rpx;">
                <view class="questionText"
                    :style="{ fontSize: fontSize + 'rpx', lineHeight: (fontSize + 12) + 'rpx', display: 'flex', flexDirection: 'row', overflow: 'auto' }">
                    <!-- <view>
						<text>{{ questionsCHildType + 1 }}、</text>
					</view> -->
                    <!-- <view style="flex: 1;">
						<rich-text :nodes="showQuestion.itemText"></rich-text>
					</view> -->
                    <u-parse :content="showQuestion.itemText" style="text-align: justify"></u-parse>
                </view>


            </view>
            <RadioQuestion v-if="['0101', '0201'].includes(showQuestion.type)" :showQuestion="showQuestion"
                :selectAnswer="selectAnswer" :windowHeight="windowHeight" :fontSize="fontSize" flag="true"
                :showAnalysis="showQuestion.stuAnswer"></RadioQuestion>
            <CheckBoxQuerstion v-else-if="showQuestion.type === '0301'" :showQuestion="showQuestion"
                :selectAnswer="selectAnswer" :windowHeight="windowHeight" :fontSize="fontSize"
                :showAnalysis="showQuestion.stuAnswer" flag="true"></CheckBoxQuerstion>
            <view v-else-if="['si01', 'si02', 'si03', 'si04', 'si06'].includes(showQuestion.type)"
                :style="{ overflow: 'auto', marginTop: '30rpx' }">
                <view class="questionTextItem">
                    <u--textarea v-model="selectAnswer" placeholder="请输入答案" autoHeight border="bottom"></u--textarea>
                </view>
            </view>

            <view v-else-if="['案例题', '情景题', '计算分析'].includes(showQuestion.itemTypeName)"
                :style="{ overflow: 'auto', marginTop: '30rpx', marginBottom: '100rpx' }">
                <view>
                    <view
                        style="width: 100%; flex-direction: row; justify-content: space-between; margin: 0rpx 0rpx 30rpx;">
                        <view @click="onAnswerItem('top', true)" class="childText" style="width: 30%;">上一小题</view>
                        <view class="childText" style="width: 36%;">
                            {{ '当前第' + (childIndex + 1) + '/' + showQuestion.children.length + '小题' }}
                        </view>
                        <view @click="onAnswerItem('bottom', true)" class="childText" style="width: 30%;">下一小题</view>
                    </view>
                    <view style="padding: 0rpx 30rpx; border-radius: 10rpx; background-color: #FFF;">
                        <view class="questionText"
                            :style="{ fontSize: fontSize + 'rpx', lineHeight: (fontSize + 12) + 'rpx', flexDirection: 'row' }">
                            <view style="margin-right: 20rpx">
                                {{ (childIndex + 1) + ' ) ' }}
                            </view>
                            <rich-text :nodes="showQuestion.children[childIndex].itemText"></rich-text>
                        </view>
                    </view>

                    <RadioQuestion v-if="['判断题', '单选题'].includes(showQuestion.children[childIndex].itemTypeName)"
                        :showQuestion="showQuestion.children[childIndex]" :selectAnswer="selectAnswer"
                        :windowHeight="windowHeight" :fontSize="fontSize"></RadioQuestion>
                    <CheckBoxQuerstion v-else-if="showQuestion.children[childIndex].itemTypeName === '多选题'"
                        :showQuestion="showQuestion.children[childIndex]" :selectAnswer="selectAnswer"
                        :windowHeight="windowHeight" :fontSize="fontSize"></CheckBoxQuerstion>
                    <view
                        v-else-if="['简答题', '填空题', '计算题', '论述题', '绘图题'].includes(showQuestion.children[childIndex].itemTypeName)"
                        :style="{ overflow: 'auto', marginTop: '30rpx' }">
                        <view class="questionTextItem">
                            <u--textarea v-model="selectAnswer" placeholder="请输入答案" autoHeight
                                border="bottom"></u--textarea>
                        </view>
                    </view>
                </view>
            </view>
            <!-- <view v-if="['0101', '0201'].indexOf(showQuestion.type)===-1" @click="onUploadStuAnswer">
				确认答案
			</view> -->
            <view v-if="isRecord || (isExhibition && showQuestion.answer && showQuestion.stuAnswer)"
                style="background: linear-gradient(180deg, #FBFFFB 0%, #F6FFF7 100%);border-radius: 12px;display: flex;align-items: center;padding:20rpx 40rpx;margin-top: 40rpx;">
                正确答案：{{ showQuestion.answer }} 您的选择：{{ showQuestion.stuAnswer || '' }}
            </view>
            <!-- <view v-if="(isRecord || isExhibition) && showQuestion.answer && showQuestion.stuAnswer"
				:style="{ padding: '30rpx 40rpx 60rpx 40rpx', backgroundColor: '#F9F9F9', marginTop: '40rpx' }">
				<view>
					<view style="display: flex;align-items: center;">
						<text>试题解析</text>
					</view>
					<view style="font-size: 14px;margin-top: 20rpx;">
						<rich-text :nodes="showQuestion.analysis ? showQuestion.analysis : '暂无'"></rich-text>
					</view>
				</view>

			</view> -->
            <view v-if="isRecord || (isExhibition && showQuestion.answer && showQuestion.stuAnswer)"
                style="margin-top: 40rpx;">
                <view style="display: flex;align-items: center;">
                    <text>试题解析</text>
                </view>
                <view style="font-size: 14px;margin-top: 20rpx;background: #F9F9F9;padding: 40rpx 20rpx;">
                    <rich-text :nodes="showQuestion.analysis ? showQuestion.analysis : '暂无'"></rich-text>
                </view>
            </view>
        </view>

        <view
            :style="{ position: 'absolute', height: '120rpx', backgroundColor: ' #fff', bottom: 0, padding: '40rpx', display: 'flex', justifyContent: 'space-around', alignItems: 'center', width: windowWidth - 40 + 'px' }">

            <u-icon name="arrow-left" size="20" @click="onAnswerItem('top', '', true)"></u-icon>
            <view style="display: flex;" @click="showExamCount = true">
                <view style="display: flex;">
                    <text class="answered"></text>
                    <text style="margin:0 40rpx 0 20rpx;">已答</text>
                </view>
                <view style="display: flex;">
                    <text class="unanswered"></text>
                    <text style="margin-left: 20rpx;">未答</text>
                </view>
            </view>
            <u-icon name="arrow-right" size="20" @click="onAnswerItem('bottom', '', true)"></u-icon>
            <view class="">{{ questionsCHildType + 1 }}/{{ allData.length }}</view>
        </view>
        <u-popup :show="showExamCount" @close="showExamCount = false" :round="0" mode="bottom">

            <view style="padding: 46rpx">
                <view style="text-align: center;">试题导航</view>
                <view style="display: flex;justify-content: space-between;margin-top: 40rpx;margin-bottom: 60rpx;">


                    <view style="display: flex;">
                        <view style="display: flex;">
                            <!-- <u-icon name="checkmark-circle-fill" size="20" color="#2B5182"></u-icon> -->
                            <text class="answered"></text>
                            <text style="margin:0 40rpx 0 20rpx;">已答</text>
                        </view>
                        <view style="display: flex;">

                            <text class="unanswered"></text>
                            <!-- <u-icon name="close-circle-fill" size="20" color="#FF3D31"></u-icon> -->
                            <text style="margin-left: 20rpx;">未答</text>
                        </view>
                    </view>
                    <view class="">{{ questionsCHildType + 1 }}/{{ allData.length }}</view>
                </view>
                <view :style="{ height: windowHeight * 0.4 + 'px', overflow: 'auto' }">
                    <u-grid :border="false" col="5">
                        <u-grid-item v-for="(item, index) in allData" :key="index">
                            <view @click="onSelectQuestion(item, index)"
                                :class="item.hasAnswer ? 'answered' : 'unanswered'"
                                :style="{ width: '60rpx', height: '60rpx', alignItems: 'center', justifyContent: 'center', borderRadius: '12rpx', color: item.hasAnswer ? '#fff' : '#999999', marginBottom: '16rpx', }">
                                {{ index + 1 }}
                            </view>
                        </u-grid-item>
                    </u-grid>

                </view>
            </view>
        </u-popup>
        <u-toast ref="uToast"></u-toast>
        <u-popup :show="submitModal" :round="10" mode="bottom" @close="submitModal = false">
            <view style="padding: 40rpx;align-items: center;text-align: center;">
                <view style="font-size: 18px;">
                    温馨提示
                </view>
                <image style="width: 421rpx;height: 320rpx"
                    src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/submit.svg"></image>
                <view style="margin-top: 40rpx;">您确认要提交试卷吗？</view>
                <view style="margin-top: 40rpx;font-size: 14px;color: #999999;">
                    为防止您误触交卷按钮，交卷时将会有3次确认弹窗,本弹窗为第{{ submitNum }}次弹窗（{{ submitNum }}/3）</view>
                <view style="margin-top: 70rpx;" @click="onSubmit">确认</view>
                <view style="width: 100%;height:10rpx;background-color: #F2F2F2;margin: 30rpx 0;"></view>
                <view @click="onClose">取消</view>
            </view>
        </u-popup>
        <u-popup :show="fontModal" mode="bottom" @close="fontModal = false; isSetUp = false" :round="10" closeable>
            <view style="padding: 40rpx;align-items: center;text-align: center;">
                <view>
                    字号设置
                </view>
                <view style="width: 100%;display: flex;align-items: center;">
                    <image style="width: 40rpx;height: 40rpx;margin-top: -20rpx;" src="@/static/images/narrow.svg"
                        mode="" @click="editFontSize(false)"></image>
                    <view style="width: 80%;margin: 60rpx 0;">
                        <u-steps :current="current" dot activeColor="#37B874">
                            <u-steps-item title="较小"></u-steps-item>
                            <u-steps-item title="标准"></u-steps-item>
                            <u-steps-item title="中等"></u-steps-item>
                            <u-steps-item title="较大"></u-steps-item>
                            <u-steps-item title="特大"></u-steps-item>
                        </u-steps>
                    </view>
                    <image style="width: 40rpx;height: 40rpx;margin-top: -20rpx;" src="@/static/images/enlarge.svg"
                        mode="" @click="editFontSize(true)"></image>
                </view>
            </view>
        </u-popup>
        <UniPopup type="center" ref="calculator" :maskClick="false" style="z-index: 1000;">
            <view style="width: 100%; height: 100%; display: flex; justify-content: center; align-items: flex-end">
                <view style="width: 90%; height: 72vh">
                    <h-calculator @closeCalculatorPopup="showCalculator" />
                </view>
            </view>
        </UniPopup>
        <!-- 闯关弹框 -->
        <u-popup :show="competitionModal" :round="10" mode="bottom" @close="submitModal = false">
            <view style="padding: 40rpx;align-items: center;text-align: center;">
                <view style="font-size: 18px;">
                    温馨提示
                </view>
                <image style="width: 421rpx;height: 320rpx"
                    src="https://qiniu-bjjrzy.bjjrzy.com/bjupi/practice/cognPractice/practice.svg"></image>
                <view style="margin-top: 40rpx;">{{ competitioText }}</view>
                <view class="btn-item" hover-class="none" hover-stop-propagation="false">
                    <view v-if="competitionStatus == 1 || competitionStatus == 4" class="btn" @click="backIndex">返回首页
                    </view>
                    <view v-else class="flex around">
                        <view class="btn btn1" @click="backIndex">返回首页</view>
                        <view class="btn btn1 btn2" @click="competitionNext">{{ competitionStatus == 2 ? '继续闯关' :
                            '重新挑战' }}</view>
                    </view>
                </view>
            </view>
        </u-popup>
        <!-- 签名弹窗 -->
        <SignPopup v-if="isSign" @success="signSuccess" @close="isSign = false"></SignPopup>
        <!-- 人脸抓拍提示 -->
        <u-modal :show="cameraTipShow" title="提示" :content='cameraTipContent'
            @confirm="cameraTipShow = false"></u-modal>
        <!-- 切屏提示 -->
        <u-modal :show="screenCutsShow" title="提示" :content='screenCutContent'
            @confirm="screenCutsShow = false"></u-modal>
        <u-loading-page fontSize="32rpx" :loading="loading" loading-text="正在加载..."></u-loading-page>
    </movable-area>
</template>

<script>
import RadioQuestion from '@/pages/common/RadioQuestion.vue'
import CheckBoxQuerstion from '@/pages/common/CheckBoxQuerstion.vue'
import { notificationFun } from '@/utils/PrjUtils.js'
import { mapDictCodes } from '@/services/ServerService.js'
import { getArrObjectByProperty } from '@/utils/PrjUtils.js'
import { getAnalysisList, getPaper, submitPaper, uploadStuAnswer } from '@/services/PracticeTestingService'
import UniPopup from '@/components/uni-popup/uni-popup.vue'
import { mapState } from 'vuex'
import SignPopup from "@/improve/components/answer/SignPopup.vue";
import { recordCutTimes, upgPracticeSign, faceRecognition, getUpgKnowledgeStatus, doUpgKnowledgeNext } from '@/improve/services'
import ExamPhoto from "@/improve/components/faciaPhoto/ExamPhoto.vue";

export default {
    components: {
        RadioQuestion,
        CheckBoxQuerstion,
        UniPopup,
        SignPopup,
        ExamPhoto
    },
    data() {
        return {
            competitionModal: false, // 竞赛弹框
            competitionStatus: 1, // 竞赛状态 1-闯关成功-全部通关 2-闯关成功-未通关 3-闯关失败-未通关 4-闯关失败-无闯关机会
            competitioJson: {}, // 获取下一关数据的参数
            isSign: false, // 签名弹框显示
            screenCuts: -1,// 当前切屏次数
            screenCutsShow: false, // 切屏提示展示
            isPhoto: false,  //是否显示拍照区域
            intervalCamera: null, // 定时抓拍
            cameraTipShow: false, // 人脸抓拍提示
            checkNum: 0, // 抓拍失败次数
            isCameraShow: false, // 是否打开摄像头
            examScores: 0, // 考试得分
            upgPracticeJoinUuid: '',
            loading: true,
            showExamCount: false,
            answer: '',
            minute: '', // 时间
            answered: 0, //已答
            unanswered: 0, //未答
            nowIndex: 0, // 下标
            seconds: 0,
            successData: {},
            childIndex: 0, // 子题 Index
            questionData: [],
            allCount: 0,
            showCount: 1,
            successCount: 0,
            signCount: 0,
            signData: [], // 标记试题数据
            showQuestion: {}, // 当前展示试题
            showQuestionChild: {}, // 当前展示试题的子题
            titleNumber: ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六"],
            selectAnswer: '',
            examVersion: 0,
            fontSize: 32, // 题目字体大小
            windowWidth: '',
            windowHeight: '',
            timer: '',
            socketToken: '',
            submitModal: false,
            submitNum: 1,
            examStatus: false,
            activeSatus: false, // 切屏控制 true时 强制交卷
            showStatus: false,
            questionTypes: [],
            type: '',
            questionNavData: [],
            showAnalysis: false,
            countDownShow: false,
            countDown: 0,
            isHistory: false,
            historyShow: false,

            mapDictCodesData: {},
            questionsType: 0,
            questionsCHildType: 0,
            allData: [],
            uuid: '',
            flag: false,
            outlineAlilityLevelId: 59,
            joinId: '',
            outLineTestId: '',
            type: 11,
            bhCheckUuid: '',
            composePlanId: '',
            version: 1,
            isRecord: false, // 是否是自测
            bhCheckId: '',
            id: '',
            title: '', //标题
            isSetUp: false, // 下拉
            automatic: false, //自动换题
            fontModal: false, // 放大缩小字体状态
            current: 0,
            calculatorShow: false, // 计算器状态
            startX: 0, // 触摸开始的X坐标
            endX: 0, // 触摸结束的X坐标
            isExhibition: false, //组卷是否展示答案
        }
    },
    onLoad(option) {

        console.log(option)

        this.onMapDictCodes()

        this.upgPracticeJoinUuid = option.upgPracticeJoinUuid
        this.bhCheckUuid = option.bhCheckUuid
        this.bhCheckId = option.bhCheckId
        this.minute = option.testTime
        this.loading = false
        this.examStatus = true
        this.title = option.title

        // this.isExhibition = JSON.parse(option.isExhibition)
        // console.log(this.isExhibition, 'isExhibition')

        this.onGetPaper(option.bhCheckUuid)

        uni.getSystemInfo({
            success: (res) => {
                this.windowWidth = res.windowWidth
                this.windowHeight = res.windowHeight
            }
        })
    },
    computed: {
        ...mapState(['practiceSettings']),
        screenCutContent() {
            return `您已切屏${this.screenCuts}次，超过${this.practiceSettings.lockTimes}次，将被强制交卷！`
        },
        cameraTipContent() {
            return `未检测到人脸，请确保人脸正对屏幕，已校验失败${this.checkNum}次，超过3次将被强制交卷`
        },
        // 考试过程中 人脸校验间隔时间
        intervals() {
            return this.practiceSettings.intervals * 60 * 1000 + 3000
        },
        competitioText() {
            return this.competitionStatus === 1 ? '恭喜您，已全部通关！' : this.competitionStatus === 2 ? '恭喜您，闯关成功，是否继续？' : this.competitionStatus === 3 ? `闯关失败，剩余${this.competitioJson.opportunity}次机会，是否重试` : '闯关失败，已无闯关次数'
        },
    },
    mounted() {
        if (this.practiceSettings.openFaceRecognize) {
            this.openPhone() // 调试阶段关闭
        }
    },
    methods: {
        backIndex() {
            uni.switchTab({
                url: '/pages/improve/improve'
            });
        },
        handleGetIsPhotoPass(base64) {
            faceRecognition({ upgPracticeJoinUuid: this.upgPracticeJoinUuid, type: 2, funcWay: 1 }, base64).then(res => {
                if (!res) {
                    this.checkNum++
                    // 校验失败（可以有三次校验机会）
                    if (this.checkNum >= 3) {
                        notificationFun('检测人脸失败3次，您即将被强制交卷！')
                        setTimeout(() => {
                            this.onSubmitPaper()
                        }, 2000)
                    } else {
                        this.cameraTipShow = true
                    }
                }
            }).catch(err => {
                console.error("校验异常")
            })
        },
        openPhone() {
            if (!this.practiceSettings.intervals) return
            this.isCameraShow = true
            this.intervalCamera = setInterval(() => {
                this.$refs.childRef.takePhoto().then(res => {
                    const base64 = 'data:image/png;base64,' + res.split(",")[1]; // 截取除头部信息以外的数据部分
                    this.handleGetIsPhotoPass(base64)
                    console.log("抓拍成功");
                }).catch(err => {
                    console.log(err)
                })
            }, this.intervals);   //每隔几分钟打开照相机 3秒截取内容
        },
        onMapDictCodes() {
            mapDictCodes('allQuestionType').then(res => {
                this.mapDictCodesData = res
            })
        },
        onChangeDict(val, dict) {
            if (dict) {
                return getArrObjectByProperty(dict, 'value', val)?.label || ''
            }
        },
        showCalculator() { // 计算器
            if (!this.calculatorShow) {
                this.calculatorShow = true
                this.$refs.calculator.open();
            } else {
                this.isSetUp = false
                this.calculatorShow = false
                this.$refs.calculator.close();
            }
        },
        onGetAnalysisList(checkId) {
            getAnalysisList({ checkId }).then(res => {
                this.isRecord = true

                this.allData = res
                this.loading = false
                this.showQuestion = res[this.questionsCHildType]
                this.selectAnswer = this.showQuestion.stuAnswer
            })

        },

        // 获取试题
        onGetPaper(bhCheckUuid) {
            console.log(bhCheckUuid, '获取试卷')
            getPaper({ bhCheckUuid }).then(res => {
                this.isRecord = false
                res.forEach((item, index) => {
                    // `<text style="border: 1px solid #37B874;border-radius: 20px 20px 20px 0;padding: 5rpx 15rpx;background-color: #F3FBF7;display:inline-block;margin:2px 5px 0 0">${this.onChangeDict(item.type, this.mapDictCodesData.allQuestionType)}</text><text style="height: fit-content;">${index + 1}、</text>`
                    item.itemText = `<text style="height: fit-content;">${index + 1}、</text>` + item.itemText
                })
                this.allData = res
                this.showQuestion = res[this.questionsCHildType]
            }).catch(err => {
                uni.navigateBack(1)
            })
        },
        // 字体放大缩小
        editFontSize(type) {
            if (type) {
                if (this.current < 4) {
                    this.current++
                    this.fontSize = (this.fontSize + 4) >= 52 ? 52 : (this.fontSize + 2)
                }

            } else {
                if (this.current > 0) {
                    this.current--
                    this.fontSize = (this.fontSize - 4) <= 20 ? 20 : (this.fontSize - 2)
                }

            }
        },
        onQueryQuestionOnExerciseNavigation(dontShow) {
            this.showExamCount = !dontShow
        },
        onUploadStuAnswer() {
            console.log(this.questionsCHildType, 'this.questionsCHildType')
            this.showQuestion.answer = this.selectAnswer
            this.allData[this.questionsCHildType].hasAnswer = this.selectAnswer
            // this.selectAnswer = this.allData[this.questionsType].items.stuAnswer[this.questionsCHildType]
            uploadStuAnswer({ checkItemId: this.allData[this.questionsCHildType].id, answer: this.selectAnswer }).then(res => {
                console.log('22222');
                this.allData.forEach(item => {
                    if (item.id === res.bhCheckItemId) {
                        item.answer = res.answer
                        item.stuAnswer = res.stuAnswer
                    }
                })
                if (this.questionsCHildType + 1 >= this.allData.length) {
                    // this.countDownShow = false
                    // this.allData[this.questionsCHildType].itemText = `<text style="background-color: #F6FFF7; height: fit-content; float: left; border-radius: 20rpx 20rpx 20rpx 0;">${this.onChangeDict(this.allData[this.questionsCHildType].type, this.mapDictCodesData.allQuestionType)}</text><text style="float: left;height: fit-content;">${this.questionsCHildType + 1}、</text>` + res.itemText
                    // this.showQuestion = this.allData[this.questionsCHildType]
                    // this.showQuestion =
                    //     this.answered = this.allData.filter(item => item.hasAnswer).length
                    // this.unanswered = this.allData.filter(item => !item.hasAnswer).length
                    // notificationFun('已经是最后一题了！')
                } else {
                    this.countDownShow = true
                    this.allData.forEach(item => {
                        if (item.id === res.bhCheckItemId) {
                            item.answer = res.answer
                            item.stuAnswer = res.stuAnswer
                        }
                    })
                    if (this.automatic) {
                        setTimeout(() => {
                            this.selectAnswer = ''
                            this.questionsCHildType += 1
                            // this.allData[this.questionsCHildType].itemText = `<text style="background-color: #F6FFF7; height: fit-content; float: left; border-radius: 20rpx 20rpx 20rpx 0;">${this.onChangeDict(this.allData[this.questionsCHildType].type, this.mapDictCodesData.allQuestionType)}</text><text style="float: left;height: fit-content;">${this.questionsCHildType}、</text>` + res.itemText
                            this.showQuestion = this.allData[this.questionsCHildType]
                            this.selectAnswer = this.showQuestion.hasAnswer || ''
                            console.log(this.showQuestion, 'this.showQuestionthis.showQuestion', this.questionsCHildType)
                            this.answered = this.allData.filter(item => item.hasAnswer).length
                            this.unanswered = this.allData.filter(item => !item.hasAnswer).length
                        }, 600)
                    }


                }
            })
        },
        onCanSubmit() {
            // this.submitNum = 1;
            this.submitModal = true
        },
        onSubmitModal() {
            this.submitModal = true
        },

        touchStart(event) {
            this.startX = event.touches[0].clientX;
        },
        touchMove(event) {
            // 移动时不做处理
        },
        touchEnd(event) {
            this.endX = event.changedTouches[0].clientX;
            if (this.endX - this.startX > 50) { // 右滑
                // this.currentQuestion = (this.currentQuestion + 1) % this.questions.length;
                console.log('右滑');

                this.onAnswerItem('top', '', true)

            } else if (this.startX - this.endX > 50) { // 左滑
                // this.currentQuestion = (this.currentQuestion - 1 + this.questions.length) % this.questions.length;
                console.log('左滑');
                this.onAnswerItem('bottom', '', true)
            }
        },
        onSubmit() {
            // 交卷

            if (this.submitNum < 3) {
                this.submitModal = false
                setTimeout(() => {
                    this.submitNum = this.submitNum + 1
                    this.submitModal = true
                }, 600)
            } else {

                this.onSubmitPaper()
            }

        },
        onClose() {
            this.submitModal = false
            this.submitNum = 1
        },
        finish() {
            notificationFun('测评时间结束，您即将被强制交卷！')
            setTimeout(() => {
                this.onSubmitPaper()
            }, 600)
        },
        competitionNext() {
            this.competitionModal = false
            doUpgKnowledgeNext(this.competitioJson).then(res => {
                uni.reLaunch({
                    url: `/improve/join/examination/index?upgPracticeJoinUuid=${res.upgPracticeJoinUuid}&id=${this.practiceSettings.id}&bhCheckId=${res.bhCheckId}&bhCheckUuid=${res.bhCheckUuid}&isPaper=true&testTime=${this.practiceSettings.time}&title=${this.practiceSettings.practiceName}`,
                })
            })
        },
        signSuccess(data) {
            upgPracticeSign({ upgPracticeJoinUuid: this.upgPracticeJoinUuid }, { base64: data }).then(res => {
                // 签名成功交卷
                notificationFun('签名成功')
                this.submitPaperSuccess()
            })
        },
        onSubmitPaper() {
            // 如果开启过程人脸验证 - 交卷 - 移除抓拍
            if (this.intervalCamera) {
                this.isCameraShow = false
                clearInterval(this.intervalCamera)
            }
            let stuAnswer = []
            for (let i = 0; i < this.allData.length; i++) {
                if (this.allData[i].hasAnswer) {
                    stuAnswer.push({
                        itemUuid: this.allData[i].uuid,
                        stuAnswer: this.allData[i].hasAnswer,
                        version: this.allData[i].version
                    })
                }
            }
            submitPaper({ checkUuid: this.bhCheckUuid }).then(res => {
                this.submitModal = false
                this.examScores = res.score
                if (this.practiceSettings.practiceType == '3') {
                    getUpgKnowledgeStatus({ bhCheckUuid: this.bhCheckUuid, upgPracticeJoinUuid: this.upgPracticeJoinUuid }).then(res => {
                        if (res.levelStatus == 2) { // 闯关失败
                            this.competitionStatus = res.opportunity > 0 ? 3 : 4
                        } else if (res.levelStatus == 3) { // 闯关成功
                            this.competitionStatus = res.lastLevel ? 1 : 2
                        }
                        this.competitioJson = { ...res }
                        this.competitionModal = true
                    })
                } else {
                    // 是否开启签名
                    if (this.practiceSettings.signConfirmFlag) {
                        notificationFun('交卷成功，请您签字确认')
                        this.isSign = true
                        return;
                    }
                    this.submitPaperSuccess()
                }
            })

        },
        // 交卷成功 跳转
        async submitPaperSuccess() {
            // 未开启分析报告和公布成绩 跳转 练习列表
            if (!this.practiceSettings.publicGrade && !this.practiceSettings.analysisReport) {
                uni.navigateTo({
                    url: `/improve/join/practiceList?practiceType=${this.practiceSettings.practiceType}`
                })
                return
            }
            // 开启公布成绩
            if (this.practiceSettings.publicGrade) {
                uni.reLaunch({
                    url: `/improve/join/examination/result?fraction=${this.examScores}&bhCheckUuid=${this.bhCheckUuid}`
                })
                return
            }
            // 开启分析报告
            if (this.practiceSettings.analysisReport) {
                uni.navigateTo({
                    url: `/improve/join/examination/analysis?bhCheckUuid=${this.bhCheckUuid}`
                })
            }
        },
        onSelectQuestion(item, index) {
            // this.onGetItem(item.itemNo)
            this.questionsCHildType = index
            this.showQuestion = this.allData[this.questionsCHildType]
            this.selectAnswer = this.showQuestion.hasAnswer ? this.showQuestion.hasAnswer : ''
            this.showExamCount = false
            // this.questionNavData[this.questionsCHildType].answer = this.selectAnswer
        },
        onShowAnalysis(isChild) {
            if (this.selectAnswer) {
                getPtAnswer(!isChild ? this.showQuestion.practiceItemUuid : this.showQuestion.children[this.childIndex]
                    .practiceItemUuid, this.selectAnswer,).then(res => {
                        console.log(res, '答题返回数据');
                        this.showQuestion = {
                            ...this.showQuestion,
                            ...res
                        }
                    })
            } else {
                return notificationFun('请选择答案后查看试题解析')
            }
            this.showAnalysis = true
            this.countDownShow = true

            setTimeout(() => {
                if (this.selectAnswer && this.showAnalysis) {
                    console.log(isChild, 'isChild')
                    this.onAnswerItem('bottom', isChild)
                }
            }, 600)


        },
        onAnswerItem(type, isChild) { // 上下题

            let nowIndex = this.questionsCHildType // 当前大题Index
            let nowChildIndex = this.childIndex // 当前小题Index
            let newIndex
            let newChildIndex

            let isLast = false

            if (type === 'bottom' && !isChild) { // 下一题 大题
                if ((nowIndex + 1) >= this.allData.length) {
                    isLast = true
                } else {

                    this.questionsCHildType = nowIndex + 1
                    console.log(this.questionsCHildType, 'console.log(this.questionsCHildType)')
                    this.showQuestion = this.allData[this.questionsCHildType]

                    // newIndex = nowIndex + 1
                    newChildIndex = 0
                }

            } else if (type === 'top' && !isChild) { // 上一题 大题
                if ((nowIndex) < 1) {
                    return notificationFun('已经是第一题了！')
                }

                this.questionsCHildType = nowIndex - 1
                this.showQuestion = this.allData[this.questionsCHildType]

                console.log(this.showQuestion, 'showQuestion')
                newChildIndex = 0
            } else if (type === 'bottom' && isChild) {
                if ((nowChildIndex) > this.allData.length) {
                    isLast = true
                }
                newChildIndex = nowChildIndex + 1
                this.questionsCHildType = nowIndex + 1
                this.showQuestion = this.allData[this.questionsCHildType]
            } else if (type === 'top' && isChild) {
                if ((nowChildIndex) < 0) {
                    return notificationFun('已经是第一题了！')
                }
                newChildIndex = nowChildIndex - 1
            }

            if (isLast) {
                return notificationFun('已经是最后一题了！')
            } else {
                this.childIndex = newChildIndex
                if (this.allData[this.questionsCHildType].hasAnswer) {
                    if (this.isRecord) {
                        this.selectAnswer = this.showQuestion.stuAnswer
                    } else {
                        this.selectAnswer = this.allData[this.questionsCHildType].hasAnswer
                    }

                    // this.showAnalysis = true 
                } else {
                    this.selectAnswer = ''
                }
            }
        },

        checkboxQuest(code) {
            let selectData = this.selectAnswer ? this.selectAnswer.split(',') : []
            if (this.selectAnswer.indexOf(code) !== -1) {
                let newArr = []
                selectData.map(item => {
                    if (item !== code) {
                        newArr.push(item)
                    }
                })
                this.selectAnswer = newArr.sort().toString()
            } else {
                selectData.push(code)
                this.selectAnswer = selectData.sort().toString()
            }
            console.log(this.selectAnswer)
        },
        onChange(data) {
            if (this.isRecord) {
                return
            }
            this.version += 1
            this.selectAnswer = data
            this.allData[this.questionsCHildType].hasAnswer = data
            this.allData[this.questionsCHildType].version = this.version
            console.log(this.allData, 'this.allData')
            this.onUploadStuAnswer()
        },

        onDeleteQuestionWrongItem() {
            deleteQuestionWrongItem(this.showQuestion.studentPracticeItemUUID).then(res => {
                this.onQueryQuestionOnExerciseNavigation(true)
                this.onGetItem(this.showQuestion.itemNo)
            })
        },
        // 切屏强制交卷
        onCutScreen() {
            this.screenCuts++
            if (this.screenCuts > 0) {
                recordCutTimes({ upgPracticeJoinUuid: this.upgPracticeJoinUuid }).then(res => {
                    if (res.locked) {
                        notificationFun('系统检测到您已切屏多次，即将被强制交卷！')
                        setTimeout(() => {
                            this.onSubmitPaper()
                        }, 1000)
                        return;
                    }
                    this.screenCutsShow = true
                })
            }
        },
    },
    onShow() {
        // 如果开启了防离开
        if (this.practiceSettings.noLeaving) {
            this.onCutScreen()
        }
    },
}
</script>

<style lang="scss">
.btn-item {
    padding-top: 20px;
    padding-bottom: 10px;
    // padding-bottom: calc(10px + env(safe-area-inset-bottom));
    // position: fixed;
    background-color: #FFFFFF;
    // box-shadow: 1px 1px 4px 2px rgba(0, 0, 0, 0.12);
    bottom: 0;
    width: 100%;
    z-index: 99;

    .btn {
        // background-color: #37B874;
        color: #37B874;
        box-shadow: 0 1px 8px 0 rgba(0, 0, 0, 0.08);
        border-radius: 24rpx;
        width: calc(100% - 40px);
        height: 90rpx;
        text-align: center;
        line-height: 90rpx;
        font-size: 32rpx;
        margin-left: 20px;
    }

    .btn1 {
        margin-left: 0;
        width: calc(50% - 20px);
    }

    .btn2 {
        background-color: #37B874;
        color: #fff;
    }

    .history {
        background-color: #FFFFFF;
        box-shadow: 1px 1px 4px 2px rgba(0, 0, 0, 0.12);
    }
}

.answered {
    width: 40rpx;
    height: 40rpx;
    border: 2rpx solid #CCC;
    text-align: center;
    line-height: 40rpx;
    display: flex;
    align-items: center;
    background-color: #37B874;
}

.unanswered {
    width: 40rpx;
    height: 40rpx;
    border: 2rpx solid #CCC;
    line-height: 40rpx;
    display: flex;
    align-items: center;
}

.questionTextItem {
    /* padding: 26rpx 50rpx; */
    font-weight: 400;
    font-size: 30rpx;
    line-height: 42rpx;
    color: #232A50;
    background: #FFF;
    border-radius: 10rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    transition: all .3s;
}

.bottomButton {
    flex: 1;
    display: flex;
    text-align: center;
    padding: 10rpx 0;
    color: #3F87FF;
    font-size: 30rpx;
    line-height: 42rpx;
    justify-content: center;
    align-items: center;
}

.u-steps-item__line {
    width: 66rpx !important;
    left: 80rpx !important;
}
</style>